package com.cn.ZhiKeDianShang.util;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cn.ZhiKeDianShang.AppConfig;
import com.cn.ZhiKeDianShang.R;
import com.cn.ZhiKeDianShang.model.response.StateAndTeamBean;
import com.cn.ZhiKeDianShang.model.response.getStateBean;
import com.cn.ZhiKeDianShang.model.response.getTeamBean;
import com.cn.ZhiKeDianShang.ui.activity.SerchlistActivity;
import com.cn.ZhiKeDianShang.util.TimeSelect.CustomDatePicker;
import com.cn.ZhiKeDianShang.util.TimeSelect.CustomTeamAndStatePicker;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.HttpUtils;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.result.ObjectResult;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.result.Result;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import okhttp3.Call;

public class WebMoreDialognew extends Dialog implements View.OnClickListener {
    TextView tvTeam;
    RelativeLayout llSelectTeam;
    TextView tvState;
    RelativeLayout llSelectState;
    TextView tvStartTime;
    TextView tvEndtime;
    TextView tvCancle;
    TextView tvCommit;
    RelativeLayout rl_select_starttime;
    RelativeLayout rl_select_endtime;

    private Context mContent;

    private BrowserActionClickListener mBrowserActionClickListener;

    //选择 团队或是状态值 弹窗传过去的数据
    List<StateAndTeamBean> mList = new ArrayList<>();


    public WebMoreDialognew(Context context, BrowserActionClickListener browserActionClickListener) {
        super(context, R.style.BottomDialog1);
        this.mContent = context;
        this.mBrowserActionClickListener = browserActionClickListener;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.slide_screen_layout);
        tvTeam = findViewById(R.id.tv_team);
        llSelectTeam = findViewById(R.id.ll_select_team);
        llSelectTeam.setOnClickListener(this);
        tvState = findViewById(R.id.tv_state);
        llSelectState = findViewById(R.id.ll_select_state);
        llSelectState.setOnClickListener(this);
        tvStartTime = findViewById(R.id.tv_start_time);
        tvEndtime = findViewById(R.id.tv_endtime);

        tvCancle = findViewById(R.id.tv_cancle);
        tvCancle.setOnClickListener(this);
        tvCommit = findViewById(R.id.tv_commit);
        tvCommit.setOnClickListener(this);

        rl_select_starttime = findViewById(R.id.rl_select_starttime);
        rl_select_starttime.setOnClickListener(this);
        rl_select_endtime = findViewById(R.id.rl_select_endtime);
        rl_select_endtime.setOnClickListener(this);

        setCanceledOnTouchOutside(true);
        Window o = getWindow();
        WindowManager.LayoutParams lp = o.getAttributes();
        //从右面出来 在从右面回去的  高度沾满屏幕
        lp.width = ScreenUtil.getScreenWidth(getContext()) - 300;
        lp.height = 5000;
        o.setAttributes(lp);
        this.getWindow().setGravity(Gravity.RIGHT);
        this.getWindow().setWindowAnimations(R.style.BottomDialog_Animation_right);
    }


    /**
     * 获取任务状态
     */
    private void getState() {
//        DialogHelper
        Map<String, String> params = new HashMap<>();
        HttpUtils.post().url(AppConfig.ORDER_TASKSTATUS)
                .params(params)
                .addSecret()
                .build()
                .execute(new BaseCallback<getStateBean>(getStateBean.class) {
                    @Override
                    public void onResponse(ObjectResult<getStateBean> result) {
//                        DialogHelper.dismissProgressDialog();
                        Log.d("Debug", "到达请求这里---");
                        if (Result.checkSuccess(mContent, result)) {
                            if (mList.size() > 0) {
                                mList.clear();
                            }
                            getStateBean data = result.getData();
                            for (int i = 0; i < data.getStatus().size(); i++) {
                                getStateBean.StatusBean statusBean = data.getStatus().get(i);
                                mList.add(new StateAndTeamBean(statusBean.getK(), statusBean.getV()));
                            }
                            TeamAndStatePicker(false, tvState.getText().toString(), mList);
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
//                        DialogHelper.dismissProgressDialog();
//                        ToastUtil.showErrorNet(LoginActivity.this);
                    }
                });
    }


    /**
     * 获取关联团队
     */
    private void getTeam() {
//        DialogHelper
        Map<String, String> params = new HashMap<>();
        HttpUtils.post().url(AppConfig.ORDER_RELATETEAM)
                .params(params)
                .addSecret()
                .build()
                .execute(new BaseCallback<getTeamBean>(getTeamBean.class) {
                    @Override
                    public void onResponse(ObjectResult<getTeamBean> result) {
//                        DialogHelper.dismissProgressDialog();
                        Log.d("Debug", "到达请求这里---");
                        if (Result.checkSuccess(mContent, result)) {
                            if (mList.size() > 0) {
                                mList.clear();
                            }
                            getTeamBean data = result.getData();
                            for (int i = 0; i < data.getTeams().size(); i++) {
                                getTeamBean.TeamsBean teamsBean = data.getTeams().get(i);
                                mList.add(new StateAndTeamBean(teamsBean.getAid(), teamsBean.getNickname()));
                            }
                            TeamAndStatePicker(true, tvTeam.getText().toString(), mList);
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
//                        DialogHelper.dismissProgressDialog();
//                        ToastUtil.showErrorNet(LoginActivity.this);
                    }
                });
    }


    CustomTeamAndStatePicker customTeamAndStatePicker;
    //选择的团队id
    String teamid;
    //选择的状态值
    String status;


    /**
     * 关联团队 以及任务状态
     */
    private void TeamAndStatePicker(boolean isSelectTeam, String selestText, List<StateAndTeamBean> data) {
        //获取当前时间
        //tvElectricalTime.setText(now.split(" ")[0]);
        Log.d("Debug", "传过来的 data为" + data.size());
        customTeamAndStatePicker = new CustomTeamAndStatePicker(mContent, isSelectTeam, selestText, data, new CustomTeamAndStatePicker.ResultHandler() {
            @Override
            public void handle(String aid, String nickname, boolean isSelectTeam) {
                if (isSelectTeam) {
                    tvTeam.setText(nickname);
                    teamid = aid;
                } else {
                    tvState.setText(nickname);
                    status = aid;
                }

            }
        }); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
        customTeamAndStatePicker.setIsLoop(); // 设置控件循环滚动 （这个在方法里面设置 相应控件能不能循环滑动）
        customTeamAndStatePicker.show(format);
    }


    CustomDatePicker customDatePicker;
    String format;
    String startTime;
    String endTime;

    /**
     * 显示时间
     */
    private void TimePicker(Boolean isStartTime) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        //获取当前时间
        format = sdf.format(new Date());
        //tvElectricalTime.setText(now.split(" ")[0]);
        customDatePicker = new CustomDatePicker(mContent, isStartTime, new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time, Boolean isStartTime) {
                Log.d("yyyyy", time);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
                if (isStartTime) {
                    startTime = time;
                    tvStartTime.setText(TimeUtil.getMyDate4(time));
                } else {
                    endTime = time;
                    tvEndtime.setText(TimeUtil.getMyDate4(time));
                }
            }
        }, "2018-01-01 00:00", format); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
        customDatePicker.showSpecificTime(false); // 不显示时和分
        customDatePicker.setIsLoop(true); // 不允许循环滚动
        if (isStartTime) {
            if (TextUtils.isEmpty(startTime)) {
                customDatePicker.show(format);
            } else {
                customDatePicker.show(startTime);
            }
        } else {
            if (TextUtils.isEmpty(endTime)) {
                customDatePicker.show(format);
            } else {
                customDatePicker.show(endTime);
            }
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_select_team:
                getTeam();
                break;
            case R.id.ll_select_state:
                getState();
                break;
            case R.id.rl_select_starttime:
                TimePicker(true);
                break;
            case R.id.rl_select_endtime:
                TimePicker(false);
                break;
            case R.id.tv_commit:
                Intent intent = new Intent(mContent, SerchlistActivity.class);
                intent.putExtra("type", 1);
                intent.putExtra("teamid", teamid);
                intent.putExtra("status", status);
                intent.putExtra("start", startTime);
                intent.putExtra("end", endTime);
                mContent.startActivity(intent);
                dismiss();
                //刷选
                break;
            case R.id.tv_cancle:
                //重置
                tvTeam.setText("");
                tvTeam.setHint("请选择");
                teamid = "";
                tvState.setText("");
                tvState.setHint("请选择");
                status = "";
                tvStartTime.setText("");
                startTime = "";
                tvEndtime.setText("");
                endTime = "";
                break;
        }
    }

    public interface BrowserActionClickListener {
        void floatingWindow();
    }

}
